﻿/* ================================================================
 * 文件名称: MainForm3
 * 作    者：于洪沣        创建时间: 2022/4/2 15:45:55
 * 版本信息: 1.0.0.0
 * ================================================================
 * 功能说明: 
 *
 *
 * ================================================================
 * 修 改 人：关键丨词         修改时间：2022/4/2 15:45:55
 * 版本信息: 1.0.0.0
 * ================================================================
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Shapes;

namespace IXXAT
{
    public partial class MainForm3 : Form
    {
        //全局定义
        #region
        public static string Address = "Address";
        public static string DataDype = "Data type";
        public static string Gain = "Gain";
        public static string Offset = "Offset";
        public static string BaseValue = "BaseValue";
        public static string Decimal = "Decimal";
        public static string Max = "Max";
        public static string Min = "Min";
        public static string Names = "参数名称";
        public static string StratBit = "Start bit";


        public static object[] a3Address = new object[len];
        public static int[] a3DataDype = new int[len];
        public static int[] a3Gain = new int[len];
        public static int[] a3Offset = new int[len];
        public static double[] a3BaseValue = new double[len];
        public static int[] a3Decimal = new int[len];
        public static double[] a3Max = new double[len];
        public static double[] a3Min = new double[len];
        public static string[] a3Name = new string[len];
        public static string[] a3Unit = new string[len];
        
        public static int[] a3StratBit = new int[len];
        public static DataSet DataSet = new DataSet();
        private static ThreadStart openfile;
        public static byte[] si = new byte[a3Address.Length];
        public static byte[] low = new byte[a3Address.Length];
        public static byte[] Subindex = new byte[a3Address.Length];
        private static byte[] Read = new byte[8];
        private static byte[] modify = new byte[8];


        public static MainForm form = new MainForm();
        //public static int rows
        public static byte[] command = new byte[2];
        public static int intright;
        public static int intleft;
        public static UInt16[] uint16buf = new UInt16[a3Address.Length];
        public static Int16[] int16buf = new Int16[a3Address.Length];
        public static string[] Slow = new string[a3Address.Length];
        public static string[] Ssi = new string[a3Address.Length];
        int[] a = new int[100];
        private static List<string> ListValue = new List<string>();

        private int tmpSelectCount = 0;
        private static string[] tmpSelectName;
        
        public MainForm3()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        #endregion
        public static int[] DgvRow = new int[100];
        //上移下移按钮
        #region
        private void MainForm3_Load(object sender, EventArgs e)
        {
            //dgvData.Rows[0].Cells[0].Selected = false;
            //dgvData.Rows[0].Selected = false;

        }
        private void Movedown_Click(object sender, EventArgs e)
        {
            try
            {
                int rows;
                //this.dgvData.MultiSelect = true;
                rows = this.dgvData.CurrentRow.Index;
                CurrencyManager cm = (CurrencyManager)BindingContext[dgvData.DataSource];
                cm.SuspendBinding(); //挂起数据绑定
                cm.ResumeBinding();
                

                this.dgvData.ReadOnly = true;

                dgvData.Rows[rows].Visible = false;
            dgvData.CurrentCell = null;
            lstViewMonitor.Items.Add(a3Name[rows]+"——已监控");
                

            for (int i = 0; i < S1.Length; i++)
                {
                    if (a3Name[rows] == S1[i])
                    {
                        S1[i] = null;
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }



        }
        public static string[] S1 = new string[len];
        private void Moveup_Click(object sender, EventArgs e)
        {
            dgvData.CurrentCell = null;
            dgvData.ClearSelection();
            for (int j = 0; j < Pubclass.PublicCache.GetData.mNumber; j++)
            {
                for (int i = 0; i < tmpSelectName.Length; i++)
                {
                    if (tmpSelectName[i].Contains("——已监控"))
                    {
                        tmpSelectName[i] = tmpSelectName[i].Replace("——已监控", "");
                    }
                    if (a3Name[j] == tmpSelectName[i])
                    {

                        dgvData.Rows[j].Visible = true;
          
                            for (int X = 0; X < S1.Length; X++)
                            {
                                if (S1[X] == null)
                                {
                                    S1[X] = a3Name[j];
                                    break;
                                }
                            }
                        while (lstViewMonitor.CheckedItems.Count != 0)
                        {
                            lstViewMonitor.Items.Remove(lstViewMonitor.CheckedItems[0]);
                        }
                    }
                }
            }
        }
        #endregion
        //cboSheet_SelectedIndexChanged
        #region
    
        private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            dgv_CellContentClick();
            CurrencyManager cm = (CurrencyManager)BindingContext[dgvData.DataSource];
            cm.SuspendBinding(); //挂起数据绑定
            dgvData.ReadOnly = true; //继续，这行可选，如果你的datagridview是可编辑的就加上
            //dgvData.SelectedRows[0].Visible = false;
            cm.ResumeBinding(); //继续数据绑定
            for (int i = 0; i < a3Address.Length; i++)
            {
                dgvData.Rows[i].Visible = false;
            }
           // dgvData.CurrentCell = dgvData.Rows[0].Cells[0];



        }
        #endregion

        //listview选中项
        #region
        private void lstViewMonitor_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            int k = 0;
            tmpSelectCount = lstViewMonitor.CheckedItems.Count;
            tmpSelectName = new string[tmpSelectCount];
            Queue<string> Q = new Queue<string>();
            for (int i = 0; i < tmpSelectCount; i++)
                if (lstViewMonitor.CheckedItems[i].Checked)
                    Q.Enqueue(lstViewMonitor.CheckedItems[i].SubItems[0].Text);
            while (Q.Count > 0)
            {
                tmpSelectName[k] = Q.Dequeue();
                k++;
            }
        }

        #endregion

        //保留小数位
        #region
        public static string RetainDecimal(double Data, int Precision)
        {
            switch (Precision)
            {
                case 1:
                    Data = Data / (float)Math.Pow(10, 1);

                    return $"{Data:F1}";

                case 2:
                    Data = Data / (float)Math.Pow(10, 2);
                    return $"{Data:F2}";

                case 3:
                    Data = Data / (float)Math.Pow(10, 3);
                    return $"{Data:F3}";

                case 4:
                    Data = Data / (float)Math.Pow(10, 4);
                    return $"{Data:F4}";

                case 5:
                    Data = Data / (float)Math.Pow(10, 5);
                    return $"{Data:F4}";

                default:
                    return $"{Data:F0}";
            }
        }
        #endregion

        //显示并读取数据
        #region 
        public static void BindDataGridView(DataTable dt, DataGridView dgv)
        {
            try
            {
                dgv.DataSource = dt;
                dt.Columns.Add("实际值", typeof(int));
                dt.Columns.Add("显示值", typeof(string));

                dgv.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        public void dgv_CellContentClick()
        {
            try
            {
                DataTable dt2 = new DataTable();
                //datagridview组件的颜色
                dgvData.RowsDefaultCellStyle.BackColor = Color.White;

                dt2 = DataSet.Tables[cboSheet.SelectedItem.ToString()];
                BindDataGridView(dt2, dgvData);
                dgvData.DataSource = dt2;

                for (int i = 0; i < this.dgvData.Columns.Count; i++)
                {
                    this.dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                //获取参数
                for (int i = 0; i < a3Address.Length; i++)
                {
                    a3Name[i] = Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pName].ToString();
                    a3Address[i] = Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pAddr];
                    a3DataDype[i] = Convert.ToInt32(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pDataType]);
                    a3Unit[i] = Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pUnit].ToString();
                    a3Gain[i] = Convert.ToInt32(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pGain]);
                    a3Offset[i] = Convert.ToInt32(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.p0ffset]);
                    a3BaseValue[i] = Convert.ToDouble(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pBase]);
                    a3Decimal[i] = Convert.ToInt32(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pDecimal]);
                    a3Max[i] = Convert.ToDouble(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pMax]);
                    a3Min[i] = Convert.ToDouble(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pMin]);
                    a3StratBit[i] = Convert.ToInt32(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pStartBit]);
                }
                for (int i = 0; i < Pubclass.PublicCache.GetData.mNumber; i++)
                {
                    if (a3Address[i].ToString().Contains("+"))
                    {
                        string str = a3Address[i].ToString().Substring(0, 1) + a3Address[i].ToString().Substring(2, 3) + "00";
                        a3Address[i] = str;
                        dgvData.Rows[i].Cells[2].Value = str;
                    }
                    while (a3Address[i].ToString().Length != 6 || a3Address[i].ToString().IndexOf(" ") > 0)
                    {
                        if (a3Address[i].ToString().IndexOf(" ") > 0)
                        {
                            dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                            MessageBox.Show("Address列下的数值有包含空格的，红色行！，请检查并关闭窗口。", "错误信息");
                            break;
                        }
                        if (a3Address[i].ToString().Length != 6)
                        {
                            dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                            MessageBox.Show("Address列下的数值有不等于六位的,绿色行！，请检查并关闭窗口。", "错误信息");
                            break;
                        }
                    }
                    if (a3Address[i].ToString().Length == 6 && a3Address[i].ToString().Substring(4, 2) != "00")
                    {
                        dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                        MessageBox.Show("Address列下的数值有最后两位不为0的,黄色行！，请检查并关闭窗口。", "错误信息");
                    }

                    Ssi[i] = a3Address[i].ToString().Substring(0, 2);
                    Slow[i] = a3Address[i].ToString().Substring(2, 2);
                    low[i] = Convert.ToByte("0x" + Slow[i], 16);
                    si[i] = Convert.ToByte("0x" + Ssi[i], 16);
                    a[i] = Convert.ToInt32("0x" + Ssi[i], 16);
                    Subindex[i] = 0;
                }
               // dgvData.Rows[0].Selected = true;
                //dgvData.Rows[(dgvData.DataSource as DataTable).Rows.Count - 1].Selected = true;
                // DataGridView取消选中第一行第一列方法(绑定数据源后)
                //dgvData.Rows[0].Cells[0].Selected = true;
                //dgvData.Rows[0].Selected = false;
                //dgvData.ClearSelection();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        #endregion

        //结构体读取CSV文件
        #region
        private void btnFilenpath_Click(object sender, EventArgs e)
        {
            OpenFile();
            
        }
        public void OpenFile()
        {
            openfile = new ThreadStart(thOpenFile);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread th = new Thread(openfile);
            th.SetApartmentState(ApartmentState.STA);
            th.Start();//启动新线程
        }
        //读取文件
        public void thOpenFile()
        {
          
            DataTable dataTable = new DataTable();
            OpenFileDialog file = new OpenFileDialog();
            file.ShowDialog();
            file.Title = @"选择要打开的文件";
            file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls|(*.csv)|*.csv";

            try
            {
                Pubclass.PublicCache.ReadTableMonitor(file.FileName);


                for (int i = 0; i < Pubclass.PublicCache.GetData.mNumber; i++)
                {
                    lstViewMonitor.Items.Add(Pubclass.PublicCache.GetInfo.ArrayMonitor[i][Pubclass.PublicCache.GetInfo.pName].ToString());
                }
                dataTable = ReadCsvToDataTable2(file.FileName);
                txtFileName.Text = file.FileName;//对话框中选择的文件名
                dataTable.TableName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
                //3：通过reader得到数据
                DataSet.Tables.Add(dataTable);
                cboSheet.Items.Clear();
                foreach (DataTable item in DataSet.Tables)
                {
                    cboSheet.Items.Add(item.TableName);
                    Console.WriteLine(item.TableName);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        #endregion       

        //读取csv文件
        #region
        public static DataColumn dataColumn;
        public static DataTable dt = new DataTable();
        public static int len = 0;
        public static DataTable ReadCsvToDataTable2(string path)
        {
            
                DataTable dt = new DataTable();
                //
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
                string strLine = "";//记录每次读取的一行记录
                string[] aryLine = null;//每行字段内容
                string[] tableHead = null;//
                int columnCount = 0;//列数
                bool IsFirst = true; //是否为第一行
                while ((strLine = sr.ReadLine()) != null)
                {
                    len++;
                    if (IsFirst == true)
                    {
                        tableHead = strLine.Split(',');
                        IsFirst = false;
                        columnCount = tableHead.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            dataColumn = new DataColumn(tableHead[i]);


                            dt.Columns.Add(dataColumn);
                        }
                    }
                    else
                    {
                        aryLine = strLine.Split(',');
                        DataRow dataRow = dt.NewRow();
                        for (int j = 0; j < columnCount; j++)
                        {
                            dataRow[j] = aryLine[j];
                        }
                        dt.Rows.Add(dataRow);
                    }
                }
                len = len - 1;
                a3Name = new string[len];
                a3Address = new object[len];
                a3DataDype = new int[len];
                a3Unit = new string[len];
                a3Gain = new int[len];
                a3Offset = new int[len];
                a3BaseValue = new double[len];
                a3Decimal = new int[len];
                a3Max = new double[len];
                a3Min = new double[len];
                a3StratBit = new int[len];
            Slow = new string[len];
                Ssi = new string[len];
                low = new byte[len];
                si = new byte[len];
                Subindex = new byte[len];
                uint16buf = new UInt16[len];
                int16buf = new Int16[len];
                S1 = new string[len];
                //tmpSelectName = new string[len];
                if (aryLine != null && aryLine.Length > 0)
                {
                    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                }
                sr.Close();
                sr.Dispose();
                fs.Close();
                fs.Dispose();

                return dt;
            
           
        
        }
        #endregion

        //读取发送
        #region
        private void timer_send_Tick(object sender, EventArgs e)
        {
            for (int j = 0; j < Pubclass.PublicCache.GetData.mNumber; j++)
            {
                for (int i = 0; i < S1.Length; i++)
                {
                    if (Pubclass.PublicCache.GetInfo.ArrayMonitor[j][(Pubclass.PublicCache.GetInfo.pName)].ToString() == S1[i])
                    {
                        Console.WriteLine("1");
                        Read[0] = 0x42;
                        Read[1] = low[j];
                        Read[2] = si[j];
                        Read[3] = Subindex[j];
                        form.DatatoSend(0x62C, Read);
                        Thread.Sleep(50);
                    }
                }
            }
            //timer_send.Enabled = false;
            //for (int j = 0; j < a3Address.Length; j++)
            //{
            //    Read[0] = 0x42;
            //    Read[1] = low[j];
            //    Read[2] = si[j];
            //    Read[3] = Subindex[j];
            //    form.DatatoSend(0x62C, Read);
            //    Thread.Sleep(50);
            //}
        }
        private void ReadValue_Click(object sender, EventArgs e)
        {
            if (ReadValue.Text == "开始")
            {
                //dgvData.CurrentCell = null;
                //dgvData.ClearSelection();

                ReadValue.Text = "停止";
                timer_send.Enabled = true;
                timer_read.Enabled = true;
                Movedown.Enabled = false;
                Moveup.Enabled = false;
            }
            else
            {
                ReadValue.Text = "开始";
                timer_send.Enabled = false;
                timer_read.Enabled = false;
                Movedown.Enabled = true;
                Moveup.Enabled = true;
            }

        }
        double Displayvalue;
        

        private void timer_read_Tick(object sender, EventArgs e)
        {
            //dgvData.CurrentCell = null;
            for (int i = 0; i < a3Address.Length; i++)
            {
                if (a3DataDype[i] == 0)
                {
                   
                    dgvData.Rows[i].Cells["实际值"].Value = MainForm.uint16resdata[i];

                    Displayvalue = (MainForm.uint16resdata[i] * a3Gain[i] + a3Offset[i]) / a3BaseValue[i];
                    dgvData.Rows[i].Cells["显示值"].Value = RetainDecimal(Displayvalue, a3Decimal[i]) + a3Unit[i];
                    double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, a3Decimal[i]));
                    //if (MainForm.uint16resdata[i] > a3Max[i])
                    //{
                    //    //timer_read.Enabled = false;
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                    //}
                    //if (MainForm.uint16resdata[i] < a3Min[i])
                    //{
                    //    //timer_read.Enabled = false;
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际值小于最小值，读取已停止！");
                    //}

                }
                if (a3DataDype[i] == 1)
                {
                    dgvData.Rows[i].Cells["实际值"].Value = MainForm.int16resdata[i];

                    Displayvalue = (MainForm.int16resdata[i] * a3Gain[i] + a3Offset[i]) / a3BaseValue[i];
                    dgvData.Rows[i].Cells["显示值"].Value = RetainDecimal(Displayvalue, a3Decimal[i]) + a3Unit[i];
                    double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, a3Decimal[i]));
                    //if (MainForm.int16resdata[i] > a3Max[i])
                    //{
                    //    //timer_read.Enabled = false;
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                    //}
                    //if (MainForm.int16resdata[i] < a3Min[i])
                    //{
                    //   // timer_read.Enabled = false;
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际值小于最小值，读取已停止！");
                    //}
                    Thread.Sleep(10);
                }
                if (a3DataDype[i] == 2)
                {
                    //Thread.Sleep(100);
                    dgvData.Rows[i].Cells["实际值"].Value = MainForm.uint16resdata[i];
                    Displayvalue = (MainForm.uint16resdata[i] * a3Gain[i] + a3Offset[i]) / a3BaseValue[i];
                    dgvData.Rows[i].Cells["显示值"].Value = StratBitNumber(MainForm.uint16resdata[i], a3StratBit[i]);
                    double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, a3Decimal[i]));
                    //if (MainForm.uint16resdata[i] > a3Max[i])
                    //{
                    //    //timer_read.Stop();
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                    //}
                    //if (MainForm.uint16resdata[i] < a3Min[i])
                    //{
                    //    //timer_read.Stop();
                    //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    //    MessageBox.Show("红色行的实际小于最小值，读取已停止！");
                    //}
                }

            }
            //timer_read.Enabled = false;

        }
        private static string StratBitNumber(UInt16 data, int StratBit)
        {
            string Data2 = Convert.ToString(data, 2).PadLeft(16,'0');

            char[] ch = Data2.ToArray();
            Array.Reverse(ch, 0, Data2.Length);
            string NewData2 = new StringBuilder().Append(ch).ToString();

            string strbit = NewData2[StratBit].ToString();
            if (strbit == "1")
            {
                return "ON";
            }
            else
            {
                return "OFF";
            }

        }
        private void dgvData_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
        {
        }

        private void dgvData_CellStyleChanged(object sender, DataGridViewCellEventArgs e)
        {

            
        }

       
    }
    #endregion
}
